package org.example; /***
 * Excerpted from "Language Implementation Patterns",
 * published by The Pragmatic Bookshelf.
 * Copyrights apply to this code. It may not be used to create training material, 
 * courses, books, articles, and the like. Contact us if you are in doubt.
 * We make no guarantees that this code is fit for any purpose. 
 * Visit http://www.pragmaticprogrammer.com/titles/tpdsl for more book information.
 ***/

import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;

public class Test {
    public static void main(String[] args) throws Exception {

        // t1的示例代码中只是恰好能展示那两张化简规则，实际中需要多次化简才能达到最简

        CharStream input = new ANTLRFileStream(Tools.getResourcePath("/t1"));

        // Create lexer/parser to build trees from stdin
        VecMathLexer lex = new VecMathLexer(input);
        CommonTokenStream tokens = new CommonTokenStream(lex);
        VecMathParser p = new VecMathParser(tokens);
        RuleReturnScope r = p.prog();   // launch parser by calling start rule
        CommonTree t = (CommonTree) r.getTree();   // get tree result

        System.out.println("Original tree: " + t.toStringTree());
        // Traverse tree down then up, applying rewrite rules
        CommonTreeNodeStream nodes = new CommonTreeNodeStream(t);
        Simplify s = new Simplify(nodes);
        t = (CommonTree) s.downup(t, true); // walk t, trace transforms
        System.out.println("Simplified tree: " + t.toStringTree());
    }
}
